#!/usr/bin/env node
var childProcess = require('./utils/child-process-wrapper.js');
var fs = require('fs');
var path = require('path');
var os = require('os');

var isWindows = process.platform === 'win32';
var productName = require('../package.json').productName;

process.chdir(path.dirname(__dirname));
var home = process.env[isWindows ? 'USERPROFILE' : 'HOME'];
var tmpdir = os.tmpdir();

// Windows: Use START as a way to ignore error if Atom.exe isnt running
var killAtomCommand = isWindows ? 'START taskkill /F /IM ' + productName + '.exe' : 'pkill -9 ' + productName + ' || true';
//childProcess.safeExec(killAtomCommand);

var pathsToRemove = [
  [__dirname, '..', 'node_modules'],
  [__dirname, '..', 'build', 'node_modules'],
  [__dirname, '..', 'apm', 'node_modules'],
  [__dirname, '..', 'atom-shell'],
  [__dirname, '..', 'electron'],
  [__dirname, '..', 'out'],
  [home, '.atom', '.node-gyp'],
  [home, '.atom', 'storage'],
  [home, '.atom', '.apm'],
  [home, '.atom', '.npm'],
  [home, '.atom', 'compile-cache'],
  [home, '.atom', 'atom-shell'],
  [home, '.atom', 'electron'],
  [tmpdir, 'atom-build'],
  [tmpdir, 'atom-cached-atom-shells'],
].map(function(pathSegments) {
  return path.resolve.apply(null, pathSegments);
});

pathsToRemove.forEach(function(pathToRemove) {
  if (fs.existsSync(pathToRemove)) {
    removePath(pathToRemove);
  }
});

function removePath(pathToRemove) {
  if (isWindows) {
    removePathOnWindows(pathToRemove);
  } else {
    childProcess.safeExec('rm -rf ' + pathToRemove);
  }
}

// Windows has a 260-char path limit for rmdir etc. Just recursively delete in Node.
function removePathOnWindows(folderPath) {
  fs.readdirSync(folderPath).forEach(function(entry, index) {
    var entryPath = path.join(folderPath, entry);
    if (fs.lstatSync(entryPath).isDirectory()) {
      removePathOnWindows(entryPath);
    } else {
      fs.unlinkSync(entryPath);
    }
  });
  fs.rmdirSync(folderPath);
};
